package com.dustedpixels.jasmin.unit.impl;

import com.dustedpixels.jasmin.unit.Unit;
import com.dustedpixels.jasmin.unit.implbase.UnitImplBase;

/**
 * A unit which multiples the cycles by specified multipler and performs
 * resulting number of cycles on wrapped unit. The effect is like the wrapped
 * unit was performing given number times faster.
 */
public final class CycleMulUnit extends UnitImplBase {
    private final Unit wrappedUnit;

    private final int multiplier;

    private int remainder;

    public CycleMulUnit(Unit wrappedUnit, int multiplier) {
        this.wrappedUnit = wrappedUnit;
        this.multiplier = multiplier;
        this.remainder = 0;
    }

    public int processSlice() {
        int wrappedUnitCycles = wrappedUnit.processCycles(multiplier
                - remainder)
                + remainder;

        int cycles = wrappedUnitCycles / multiplier;

        remainder = wrappedUnitCycles % multiplier;

        return cycles;
    }

    public int processCycles(int cycles) {
        int wrappedUnitCycles = wrappedUnit.processCycles(cycles * multiplier
                - remainder)
                + remainder;

        cycles = wrappedUnitCycles / multiplier;

        remainder = wrappedUnitCycles % multiplier;

        return cycles;
    }
}
